import { makeAutoObservable, runInAction } from 'mobx'
import { queryTrainDetail, fetchDict, getPlanInfo, checkPlan } from '../api'
import type { TrainInfo, Plan, FormData } from '../api/interface'
import { history } from 'umi'
import { Toast } from 'antd-mobile'

class Store {
    info: Plan | null = null
    public trainDetail: Partial<TrainInfo> = {}
    /** 专业大类 */
    majorDict: Record<string, string> = {}

    /** 培训级别 */
    levelDict: Record<string, string> = {}
    constructor() {
        makeAutoObservable(this)
        this._init()
        this._initMajorList()
        this._initLevelList()
    }
    queryDetail = async (id: number) => {
        const res = await queryTrainDetail(id)
        if (res.data) {
            this.trainDetail = (res.data as unknown) as TrainInfo
        }
    }
    /**
     * 初始化专业大类
     */
    private _initMajorList = async () => {
        return fetchDict('major')
            .then(({ data }) => {
                runInAction(() => {
                    this.majorDict = data
                })
            })
            .catch(() => {})
    }

    /**
     * 初始化培训等级
     */
    private _initLevelList = async () => {
        return fetchDict('level')
            .then(({ data }) => {
                runInAction(() => {
                    this.levelDict = data
                })
            })
            .catch(() => {})
    }

    /**
     * 初始化
     */
    private _init = () => {
        console.log(history)
        const id = history.location.state?.id

        if (id !== undefined) {
            getPlanInfo({ id: Number(id) })
                .then(({ data }) => {
                    data.subdata.forEach((item, i) => {
                        item.sort_id = i + 1
                    })

                    this.info = data
                })
                .catch(() => {})
        }
    }

    /**
     * 提交审核
     */
    onSubmit = (formData: FormData, setSuccVisible?: () => void) => {
        const id = history.location.state?.id

        if (id !== undefined) {
            return checkPlan({ id: Number(id) }, formData)
                .then(() => {
                    Toast.show('提交成功')
                    history.goBack()
                    setSuccVisible && setSuccVisible()
                })
                .catch(() => {})
        }
    }
}

export default Store
